/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simplepushserver.filesend;

import simplepushserver.filesend.ByteBlockReciver;
import java.io.*;
import java.net.*;
import simplepushserver.filesend.TransferProgressBar;

/**
 *
 * @author Fille
 */
public class FileReceiver extends Thread{
    public static int BLOCKSIZE=8192;
    TransferProgressBar StatusBar;
    private long filesize=0;
    private int numberOfFilesLeft=0;
    private String filnamn="";
    private File currentfile;
    private File desFolder;
    private Socket socket;
    boolean svar = false;
    InputStream in;

    public FileReceiver(File desFolder, Socket socket, TransferProgressBar StatusBar) throws IOException{
       this.desFolder=desFolder;
       this.socket=socket;
       this.StatusBar=StatusBar;
       setName("FileSender");
    }
    public void runRaw(){
        try{
            DataOutputStream dataUt = new DataOutputStream(socket.getOutputStream());
            DataInputStream dataIn = new DataInputStream(socket.getInputStream());
            numberOfFilesLeft = dataIn.readInt();
            int numberOfFiles = numberOfFilesLeft;
            print(numberOfFilesLeft+" is to be received");
        do{
            try{
                StatusBar.stat.setTimeText(0);
                StatusBar.setVisible(true);
                StatusBar.startTime();
                print(numberOfFilesLeft+"¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤");
                filesize=dataIn.readLong();
                print("#Filesize recived = "+filesize);
                if(filesize<0) {
                        throw new ArithmeticException("Filesize less than zero");
                }else{
                    print("#Filesize: "+String.format("%3.2f",(double)filesize/1024/1024)+"MB ("+filesize+")");
                    dataUt.writeBoolean(true);       
                }
                BLOCKSIZE=0;
                BLOCKSIZE=dataIn.readInt();
                print("#Blocksize recived = "+BLOCKSIZE);
                if(BLOCKSIZE<0){
                    dataUt.writeBoolean(false);
                    throw new ArithmeticException("Blocks less than zero");
                }else{
                    dataUt.writeBoolean(true);
                }
                StatusBar.setMaxValue(filesize);
                char temp;
                filnamn="";
                while((temp = dataIn.readChar()) != '|') {
                        filnamn += temp;
                }
                print("#Recived filename: "+filnamn);
                dataUt.writeBoolean(true);
                if(filnamn.length()>100){
                    System.out.println("##### = "+filnamn.length());
                    return;
                }
                currentfile=new File(desFolder.getAbsolutePath(),filnamn);
                
                print("New File's Path: \""+currentfile.getParent()+"\" <- \""+currentfile.getName()+"\"");
                StatusBar.setFilename(currentfile.getName());
                StatusBar.setTitle("Downloading "+numberOfFilesLeft+" of "+numberOfFiles);
                currentfile.getParentFile().mkdirs();
                //currentfile.getAbsoluteFile().createNewFile();
                FileOutputStream fileOut = new FileOutputStream(currentfile);
                
                StatusBar.setMaxValue(filesize);
 
                long bytesLeftToRead = filesize;
                long bytesReceived = 0;
                byte[] readByteArray;
                dataUt.writeBoolean(true);
                boolean bytesleft=true;
                do{// Receiver
                    if(bytesLeftToRead<=BLOCKSIZE && bytesLeftToRead>0){
                        BLOCKSIZE = (int)bytesLeftToRead;
                        bytesleft=false;
                    }
                    readByteArray = new byte[BLOCKSIZE];
                    dataIn.read(readByteArray);
                    fileOut.write(readByteArray);
                    bytesLeftToRead-=readByteArray.length;
                    bytesReceived+=readByteArray.length;
                    StatusBar.updateTo(bytesReceived);
                }while(bytesleft);

                dataUt.flush();
                StatusBar.stopTime();
                fileOut.flush();
                fileOut.close();
                dataUt.writeBoolean(true);
                print("Sending recive comf..."+dataIn.readBoolean());
                
                print(numberOfFilesLeft+"¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤END¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤");
                StatusBar.updateTo(filesize);
                StatusBar.stopTime();

                Thread.sleep(1000);
                numberOfFilesLeft--;

            } catch (Exception ioe) {
                ioe.printStackTrace();
                return;
                
            }
        }while(numberOfFilesLeft>0);
        dataIn.close();
        dataUt.close();
        }catch(Exception ioe){
            ioe.printStackTrace();
        }
    }
    public void run(){
        try {
            in = socket.getInputStream();
            desFolder.mkdirs();
            File newZipFile = File.createTempFile("","",desFolder);
            BufferedOutputStream out =  new BufferedOutputStream(new FileOutputStream(newZipFile));
            ByteBlockReciver bbh = new ByteBlockReciver(in, out , BLOCKSIZE);
            print("Runnning..");
            bbh.run();
            print("Finnished");
            socket.close();
            out.close();
            in.close();
            print("Extracting");
            Zipper.unZip(newZipFile, desFolder);
            print("Done");
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }



    private void print(String text){
        System.out.println(this.getClass().getName()+" : "+text);
    }
    
}
